﻿@page "/docs/{fileName}"
@page "/docs"

@using AntDesign.Docs.Services
@using AntDesign.Docs.Highlight

@inject NavigationManager NavigationManager
@inject ILanguageService LanguageService
@inject DemoService DemoService
@inject IPrismHighlighter PrismHighlighter
@inject HttpClient HttpClient;

<MainContent>
    <article class="markdown">
        @if (file != null)
        {
            <h1>@file.Title</h1>
            @((MarkupString) @file.Html)
        }
    </article>
</MainContent>

@code {

    [Parameter] public string fileName { get; set; }

    DocsFile file;

    string currentLanguage => LanguageService.CurrentCulture.Name;

    protected override async Task OnInitializedAsync()
    {
        await SetDocUrl();
        NavigationManager.LocationChanged += async (_, args) => await SetDocUrl();
    }

    private async ValueTask SetDocUrl()
    {
        if (!string.IsNullOrEmpty(fileName))
        {
            var baseUrl = NavigationManager.ToAbsoluteUri(NavigationManager.BaseUri);
            var docUrl = new Uri(baseUrl, $"_content/AntDesign.Docs/docs/{fileName}.{currentLanguage}.json").ToString();
            file = await this.HttpClient.GetFromJsonAsync<DocsFile>(docUrl);
            StateHasChanged();
        }
        else
        {
            var currentUrl = NavigationManager.ToBaseRelativePath(NavigationManager.Uri);
            var newUrl = currentUrl.IndexOf('/') > 0 ? currentUrl.Substring(currentUrl.IndexOf('/') + 1) : currentUrl;
            var menus = await DemoService.GetMenuAsync();
            var current = menus.FirstOrDefault(x => x.Url == newUrl);
            if (current != null)
            {
                NavigationManager.NavigateTo($"{currentLanguage}/{current.Children[0].Url}");
            }
        }
    }


    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await PrismHighlighter.HighlightAllAsync();
    }

}
